'use strict';

import app from '../app'
import redisHandle from '../handle/redisHandle';

class GameDao {
    handle: any
    constructor(db) {
        this.handle = db.collection("game")

    }

    init = async (): Promise<any> => {
        let doc = await this.findOne({ index: 1 })
        if (!doc) {
            redisHandle.set(app.config.gameName + 'version', '1.1')
            await this.handle.insertOne({
                index: 1,
                version: '1.1',
                minVersion: '1.1'
            })
        } else {
            app.version = doc.version || '1.1'
            redisHandle.set(app.config.gameName + 'version', app.version)
            app.minVersion = doc.minVersion || '1.1'
            let minVersion = app.minVersion.split('.')
            app.minMax = Number(minVersion[0])
            app.minMin = Number(minVersion[1])
            app.serverState = doc.serverState || 0
            app.stateText = doc.stateText || "服务器在维护中"
            await this.handle.updateOne({
                index: 1
            }, {
                $set: {
                    index: 1,
                    version: app.version,
                    minVersion: app.minVersion,
                    serverState: app.serverState,
                    stateText : app.stateText
                }
            });
        }

    }
    findOne = async (query): Promise<any> => {
        return await this.handle.findOne(query)
    }

    find = async (query): Promise<any[]> => {
        return await this.handle.find(query).toArray()
    }

    findByPage = async (query, start: number, size: number): Promise<any[]> => {
        return await this.handle.find(query).skip(start).limit(size).toArray()
    }

    findByPageAndSort = async (query, sort, start, size): Promise<any[]> => {
        return await this.handle.find(query).sort(sort).skip(start).limit(size).toArray()
    }
    //opts  { multi: true}
    updateMany = async (query, data): Promise<any> => {
        return await this.handle.updateMany(query, data);
    }

    updateOne = async (query, data): Promise<any> => {
        return await this.handle.updateOne(query, data);
    }
    count = async (query): Promise<number> => {
        return await this.handle.countDocuments(query)
    }

    remove = async (query): Promise<any> => {
        return await this.handle.remove(query, {
            multi: true
        });
    }
}

export default GameDao